package com.yuan.ayuancity.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yuan.ayuancity.controller.common.CaptchaController;
import com.yuan.ayuancity.entity.Admins;
import com.yuan.ayuancity.entity.Users;
import com.yuan.ayuancity.mapper.UsersMapper;
import com.yuan.ayuancity.service.UsersService;
import com.yuan.security.SecurityUser;
import com.yuan.view.BcryptHelper;
import com.yuan.view.JwtHelper;
import com.yuan.view.YuancityView;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author asuyuan
 * @since 2023-02-07
 */
@RestController
@RequestMapping("/ayuancity/users")
@CrossOrigin
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Resource
    private UsersMapper usersMapper;

    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    public YuancityView list(Users Users,
                              @RequestParam(value ="pageNum",required = false,defaultValue = "1")int page,
                              @RequestParam(value="pageSize",required = false,defaultValue = "5")int size)
    {

        PageInfo<Users> list =usersService.selectUsersList(page,size,Users);
        return YuancityView.success("查询成功").put("data", list);
    }


    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/{userId}")
    public YuancityView getInfo(@PathVariable("userId") Long userId)
    {
        Users users = usersService.selectUsersByUserId(userId);
      return YuancityView.success("查询成功").put("data",users);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public YuancityView add(@RequestBody Users users)
    {
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_account", users.getUserAccount());
        Users olduser = usersMapper.selectOne(queryWrapper);
        if (olduser!=null){
            return YuancityView.failure("账户已存在");
        }
        //加密
        String encrypt = BcryptHelper.bcrypt(users.getUserPassword());
        users.setUserPassword(encrypt);
        usersService.insertUsers(users);
        return YuancityView.success("添加成功");
    }


    @ApiOperation("前端注册用户")
    @PostMapping("/registerUser")
    public YuancityView registerUser(HttpServletRequest request,
                                     String userAccount,String userPassword,String  email,String kaptcha)
    {
        HttpSession session = request.getSession();
        Object codeInSession = session.getAttribute("eamilcode");
        if (codeInSession==null||!kaptcha.equals(codeInSession)){
            return YuancityView.failure("验证码不正确");
        }
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        Users olduser = usersMapper.selectOne(queryWrapper);
        if (olduser!=null){
            return YuancityView.failure("账户已存在");
        }
//        //加密
        String encrypt = BcryptHelper.bcrypt(userPassword);
        Users users=new Users();
        users.setUserPassword(encrypt);
        users.setUserAccount(userAccount);
        users.setUserName(userAccount);
        users.setUserEmail(email);
        usersService.insertUsers(users);
        return YuancityView.success("添加成功");
    }



    /**
     * 修改用户
     */
    @PutMapping
    public YuancityView edit(@RequestBody Users users)
    {
        //TODO 目前打算查询数据库密码与现在密码是否一致，不一致则修改==》加权限，非admin不给看修改密码框
        //TODO 后期把修改密码单独做个接口
        Users olduser = usersMapper.selectUsersByUserId(users.getUserId().longValue());
        //BcryptHelper.matches( users.getUserPassword(),olduser.getUserPassword())
        //前端已经加密过了
        if (users.getUserPassword()!=null && !olduser.getUserPassword().equals(users.getUserPassword())){
            //前端传过来的密码和数据库不一致，则加密前端的密码
            String encrypt = BcryptHelper.bcrypt(users.getUserPassword());
            users.setUserPassword(encrypt);
        }
        usersService.updateUsers(users);

        //更新token
        Users datauser=usersMapper.selectUsersByUserId(users.getUserId().longValue());
        JwtHelper jwtHelper=new JwtHelper();
        SecurityUser details=new SecurityUser(datauser);
        String userToken = jwtHelper.createUserToken(details, new Users());
        Claims claimsByToken = jwtHelper.getClaimsByToken(userToken);
        System.out.println("修改用户，更新token==="+claimsByToken);

        return YuancityView.success("修改成功").put("token", userToken);
    }

    @PostMapping("/editUserPwd")
    public YuancityView editUserPwd(String userId,String oldpwd,String newpwd)
    {
        //查询数据库
        Users users = usersService.selectUsersByUserId(Long.parseLong(userId));
        //比较
        if (BcryptHelper.matches( oldpwd,users.getUserPassword())){
            //前端传过来的密码和数据库一直
            String encrypt = BcryptHelper.bcrypt(newpwd);
            //修改
            Users users1=new Users();
            users1.setUserId(Integer.parseInt(userId));
            users1.setUserPassword(encrypt);
            usersMapper.updateUsers(users1);
            return YuancityView.success("修改成功");
        }
        return YuancityView.failure("密码错误");
    }


    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    public YuancityView remove(@PathVariable Long[] userIds)
    {
        usersService.deleteUsersByUserIds(userIds);
        return YuancityView.success("删除成功");
    }
}

